<?php

// TODO: TYPES:
//

/**
 * class multitender_action_detail
 * @author Paul
 */
class multitender_action_detail extends multitender_action {

    function run() {

        /* LIKEs */
        $document = &JFactory::getDocument();

        $user = $this->conf['user'];
        $user_id = isset($user['id']) ? $user['id'] : null;
        $id = isset($_GET['id']) ? (int) $_GET['id'] : 20300;

        $detailModel = $this->new_model('detail');

        $item = $detailModel->get($id);

        if (empty($item)) {
            header($_SERVER["SERVER_PROTOCOL"] . " 404 Not Found");
            exit;
        }


        $MSK0 = ADONewConnection('mysql://mt:90210@msk0.multitender.ru/tenders15');
        $MSK0->Execute('set names utf8');
        $id = $MSK0->GetOne('SELECT id FROM tender WHERE purchaseNumber=?', array($item['num']));
        if ($id != 0) {
            header("Location: http://{$_SERVER['HTTP_HOST']}/tenders/detail44/?purchaseNumber={$item['num']}");
            exit();            
        }
        $MSK0 = NULL;

        $this->conf['full'] = false;
        $this->conf['detail_public'] = false;

        if ($user_id > 99) {
            // Сохранение в просмотренных тендерах
            $bl = new multitender_model_billing();
            $bl->view_usertender($user_id, $id);

            $user_tender = $bl->get_usertender($user_id, $id);
            $access = $bl->getAccess($user_id);

            // Проверка, может тендер куплен
            if (($user_tender) && (!is_null($user_tender['date_purches']))) {
                $this->conf['full'] = true;
            } else {
                if ($access) {
                    if (time() < strtotime($access['todate'])) {
                        $this->conf['full'] = true;
                        $bl->buy_usertender($user_id, $id, 1);
                        $user_tender['date_purches'] = date("Y-m-j H:i:s");
                    } else {
                        $this->conf['full'] = false;
                    }
                }
            }
            $user_tender['date_purches'] = date2str($user_tender['date_purches']);
            if ($access) {
                if (time() < strtotime($access['todate'])) {
                    $access['limit'] = 1;
                } else {
                    $access['limit'] = 0;
                }
            }
            $access['todate'] = date2rus($access['todate']);

            $ft = $this->new_action("favorite_tenders");
            $item['favorite'] = $ft->get_status();
        }


        // публичный?
        // проверку публичности нужно перенесести выше, нет смысла приобретать тендер
        // в публичном доступе
        if ((strtotime($item['date']) > 1) && ( strtotime($item['date']) < (time() - 45 * 24 * 3600 ) )) {
            $this->conf['detail_public'] = true;
            $this->conf['full'] = true;
        }

        $docs = array();
        $detail = array();

        // AIR FIX: Для зареганых без оплаты выводим доки без ссылки
        if ($user_id) {
            if (!preg_match('/^http/', $item['site_doc_link']) && !is_null($item['site_doc_link'])) {
                $link_base = str_ireplace('http://', '', $item['site_url']);
                $link_base = 'http://' . preg_replace('#/.*#ui', '', $link_base);
                $item['site_doc_link'] = $link_base . '/' . $item['site_doc_link'];
            }

            $docs = $detailModel->getDoc($id);

            foreach ($docs as &$doc) {

                if (!$this->conf['full']) {
                    $doc['name'] = preg_replace("#\d#si", "X", $doc['name']);
                }

                if ($doc['md5']) {
                    $doc['link'] = 'http://arh.multitender.ru/doc/?md5=' . $doc['md5'];
                    $doc['size'] = sprintf('%.2f', $doc['size'] / (1024 * 1024)) . "\xC2\xA0MB";
                } else {
                    if (preg_match('/^http/i', $doc['detail_link'])) {
                        $doc['link'] = $doc['detail_link'];
                    } elseif ($item['site_doc_link']) {
                        $doc['link'] = str_ireplace('#ID#', $doc['internal_id'], $item['site_doc_link']);
                        $doc['link'] = str_ireplace('#detail_link#', $doc['detail_link'], $doc['link']);
                        $doc['link'] = preg_replace('#/{2,}#', '/', $doc['link']);
                        $doc['link'] = str_ireplace('http:/', 'http://', $doc['link']);
                    }
                }
            }
        }

        $subs = $this->new_action('subscribe');
        $freesubscribe = $subs->freenewsletter();


        // nrzi restruct
        if ($this->conf['full']) {
            $detail = $detailModel->getDetail($id);

            if (!empty($item['other'])) {
                $other = unserialize($item['other']);
            } elseif (!empty($detail['other'])) {
                $other = unserialize($detail['other']);
            }

            if ($detail['is_cached'] == 1) {
                $detail['is_cached'] = md5($detail['id'] . 'SOLT:CACHE-DETAIL:90210');
            }

            if (!empty($other)) {
                $item['other'] = array();
                foreach ($other as $k => $v) {
                    if ($k == 'Документы')
                        break;
                    $item['other'][$k] = $v;
                }
            }
        }

        if (!preg_match("/^http/", $item['site_url'])) {
            $item['site_url'] = 'http://' . $item['site_url'];
        }
        if (preg_match("#^/#", $item['site_detail_link'])) {
            $item['site_detail_link'] = $item['site_url'] . $item['site_detail_link'];
        }
        //http://krasgz.ru/torgi/?action=view&id=#ID#
        if (empty($item['detail_link'])) {

            if (!preg_match('/^http/', $item['site_detail_link'])) {
                $link_base = str_ireplace('http://', '', $item['site_url']);
                $link_base = 'http://' . preg_replace('#/.*#ui', '', $link_base);
                $item['site_detail_link'] = $link_base . '/' . $item['site_detail_link'];
            }

            $item['link'] = str_ireplace('#ID#', $item['internal_id'], $item['site_detail_link']);
            $item['link'] = str_ireplace('#INTERNAL_ID#', $item['internal_id'], $item['link']);
            $item['link'] = str_ireplace('#PREFIX#', $item['detail_link_prefix'], $item['link']);
            $item['link'] = str_ireplace('#NUM#', $item['num'], $item['link']);
            $item['link'] = str_ireplace('#NUM_WIN#', urlencode(mb_convert_encoding($item['num'], 'CP1251', 'UTF-8')), $item['link']);

            // удаляем повторы автоматом
            $item['link'] = preg_replace('#/{2,}#', '/', $item['link']);
            $item['link'] = str_ireplace('http:/', 'http://', $item['link']);
            $item['link'] = str_ireplace('https:/', 'https://', $item['link']);
        } else {
            $item['link'] = $item['detail_link'];
        }
        // Счетчик переходов
        //$item['away_link'] = '/tenders/away/?site_id=' . $item['site_id'] . '&go=' . urlencode($item['link']);
        $item['away_link'] = $item['link'];

        $tpl = $this->new_tpl();

        //$ctx = stream_context_create(array('http' => array( 'timeout' => 2 ))));
        $ext = file_get_contents("http://win.multitender.ru/?controller=tender&purchaseNumber={$item['num']}&tmpl=json", false, $ctx);
        if ($ext) {
            $ext = reset(json_decode($ext, TRUE));
            if (!empty($ext)) {
                if ($user_id) {
                    $sc = $this->new_model('subscribe_customer');
                    foreach ($ext['lots'] as $key1 => $lot) {
                        foreach ($lot['customers'] as $key2 => $customer) {
                            if (isset($customer['inn'])) {
                                $ext['lots'][$key1]['customers'][$key2]['status'] = $sc->check($user_id, $customer['inn']);
                            }
                        }
                    }
                }
                $tpl->assign('ext', $ext);
            }
        }

        $item_name = $item['name'];
        $item_now = $item;

        $this->conf['page_title'] = $item['name'];

        $tpl->assign('username', $user['name']);

        $tpl->assign('user_id', $user_id);
        if (!empty($user_tender)) {
            $tpl->assign('purches', $user_tender);
        }
        if (!empty($access)) {
            $tpl->assign('access', $access);
        }

        $tpl->assign('user', $user);
        $tpl->assign('docs', $docs);
        $tpl->assign('item', $item);
        $tpl->assign('conf', $this->conf);
        $tpl->assign('name', @$_GET['name']);
        $tpl->assign('detail', $detail);
        $tpl->assign('freesubscribe', $freesubscribe);


        if (strtotime($item['date_end']) > time()) {
            $tpl->assign('actual', true);
        }


        //$tpl->assign('similar', $this->similar($item['region_id']));
        //$this->similar_new();
        // $tpl->assign('customer', $this->customer($item['customer_id']));
        $tpl->assign('like_customer_link', 'http://multitender.ru/tenders/?search[customer][' . $item['customer_id'] . ']');
        //$tpl->assign('region', $this->region($item));

        $tpl->assign('task', @$_GET['task'] ? $_GET['task'] : '');
        $tpl->assign('comments', tenders_run_action('detail_comment'));
        //$tpl->assign('baners', tenders_run_action('banerrota'));

        $app = & JFactory::getApplication();
        $pathway = & $app->getPathway(); // получаем объект СН для модификации
        $pathway->addItem($item['name']);  // добавляем название раздела         

        if (isset($_POST['form']) && (preg_match('/party|constalt/si', $_POST['form']))) {

            if ($_POST['form'] == 'party') {
                $subject = "Запрос на помощь в торгах";
            } else {
                $subject = "Запрос на консультацию";
            }
            $html = $tpl->fetch("detail.{$_POST['form']}.send.tpl");
            $email = $this->new_model('email');
            $email->send($subject, $html, 'airrussian@mail.ru', 'subscribe@multitender.ru');
            $email->send($subject, $html, 'order@sbaspect.ru', 'subscribe@multitender.ru');
        }


        return $tpl->fetch('detail.tpl');
    }

    function similar($region_id) {
        $result['view'] = "К сожалению, похожих тендеров не найденно";

        $like = $this->new_tpl();

        $s_obj = new multitender_model_search();
        $s_obj->SetSearch(array('reg' => array($region_id => true)));
        $s_obj->onpage = 5;
        $s_obj->kostyl_type = 'detail_last';

        $result['link'] = $this->conf['pref']['link_base'] . $s_obj->to_url();

        $r = $s_obj->query();

        $items = $r['items'];
        if ($items) {
            foreach ($items as &$item) {
                $item['link'] = $this->conf['pref']['link_detail'] . $item['id'];
                $tenders[] = $item['id'];
            }
            $like->assign('items', $items);
            $result['view'] = $like->fetch('list.tpl');
        }
        return $result;
    }

    function similar_new() {
        $s_obj = new multitender_model_search();
        $sim = $s_obj->similar_sphinx($item_now['name'], $item_now['id']);

        if (empty($sim))
            break;

        foreach ($sim as &$item_sim) {
            $item_sim['link'] = $this->conf['pref']['link_detail'] . $item['id'];
        }

        $like = $this->new_tpl();
        $like->assign('items', $sim);
        if (empty($sim)) {
            $tpl->assign('like_new', 'К сожалению, похожих тендеров не найденно');
        } else {
            $tpl->assign('like_new', $like->fetch('list.tpl'));
        }
    }

    function customer($customer_id) {
        $result['view'] = 'К сожалению, похожих тендеров не найденно';
        if ($customer_id) {
            $s_obj = new multitender_model_search();
            $s_obj->SetSearch(array('customer' => array($customer_id => true)));
            $s_obj->onpage = 5;

            $r = $s_obj->query();

            $result['link'] = $this->conf['pref']['link_base'] . $s_obj->to_url();

            $items = $r['items'];
            if (!empty($items)) {
                foreach ($items as &$item) {
                    $item['link'] = $this->conf['pref']['link_detail'] . $item['id'];
                }
                $like = $this->new_tpl();
                $like->assign('items', $items);
                $result['view'] = $like->fetch('list.tpl');
            }
        }
        return $result;
    }

    function region($current_item) {
        require_once $this->conf['libdir'] . '/morf.php';
        $crc = implode(',', morf_crc($current_item['name']));
        if (empty($crc)) {
            return false;
        }

        $lemma_ids = $this->db->GetCol('select lemma_crc from morf_words where crc in (' . $crc . ')');
        if (empty($lemma_ids)) {
            return false;
        }

        $lemma_txt = implode(',', $lemma_ids);
        $lemma_ids = $this->db->GetCol('select crc from morf_lemmas where crc in (' . $lemma_txt . ') AND ignor = 0');
        if (empty($lemma_ids)) {
            return false;
        }

        $lemma_txt = implode(',', $lemma_ids);

        if (!isset($current_item['region_id'])) {
            $RegMin = 1;
            $RegMax = 100;
        } else {
            $RegMin = (Ceil($current_item['region_id'] / 100) - 1) * 100 + 1;
            $RegMax = Ceil($current_item['region_id'] / 100) * 100;
        }

        $item_ids = $this->db->GetCol('SELECT DISTINCT item_id FROM morf_xef_item WHERE lemma_crc IN (' . $lemma_txt . ') ORDER BY item_id DESC LIMIT 5');
        if (empty($item_ids)) {
            return false;
        }

        $item_txt = implode(',', $item_ids);
        $items = $this->db->GetArray('SELECT item.*, type.name as type_name, site.name as site_name, region.name as region_name ' .
                'FROM item ' .
                'LEFT JOIN type ON type.id = item.type_id ' .
                'INNER JOIN site ON item.site_id = site.id ' .
                'INNER JOIN region ON item.region_id = region.id ' .
                'WHERE item.id IN (' . $item_txt . ') ' .
                'AND (item.region_id>=' . $RegMin . ' AND item.region_id<=' . $RegMax . ') ' .
                'ORDER BY id DESC LIMIT 5 ');

        if (empty($items)) {
            return false;
        }

        foreach ($items as &$item) {
            $item['link'] = $this->conf['pref']['link_detail'] . $item['id'];
        }

        $like = $this->new_tpl();
        $like->assign('items', $items);
        $result['view'] = $like->fetch('list.tpl');
        $result['link'] = $this->conf['pref']['link_base_http'] . 'tenders/region/' . $current_item['region_id'];

        return $result;
    }

}
